import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);
var stopAutoLoginTimeSize = 5000;//五秒内不再重复登录
var loginHistory = {};//记录登录页面时间，两次访问登录页面的时间小于某值则停止自动登录，否则会不断循环

//登录页对应账号
var suportUrls = {
  'https://mailsso.mxhichina.com/login.htm': {
    dest: 'https://qiye.aliyun.com/',
    appName: 'alyx',
  }
}

//需要跳转的地址
var needToUrls = {
  'https://qiye.aliyun.com/alimail/auth/login': 'https://mailsso.mxhichina.com/login.htm?app_code=smartmail&lang=zh_CN&redirect_url=https%3A%2F%2Fqiye.aliyun.com%2Falimail%2Fauth%2FcallbackForCore%3Freurl%3D%252Falimail%252F&network_env=1&sign=51c1313f895e8148f336e9e38755cb64&device_id=8f6f1d51255447c39a7f4251c943e3c2',
}

// 访问这里|将会跳转到这里
var tologinUrls = {
  "https://qiye.aliyun.com/": "https://qiye.aliyun.com/alimail/auth/login",
}

var initUrl = false//是否初始化

var urlTag = {
  alyx: 'https://qiye.aliyun.com/',
  cd: ""
}

// 加工对象
var handler = {
  mybug: urlTag.cd + 'my-bug.html',//禅道 我的bug
  bugBrowse: urlTag.cd + 'bug-browse',//禅道bug
  bugView: urlTag.cd + 'bug-view',//禅道bug
  taskView: urlTag.cd + 'task-view',//禅道任务详细
}


var ut = {
  //加工网页
  doScript(url, webView) {
    initUrlSetting();
    if (url.indexOf(urlTag.cd) >= 0) {
      if (url.indexOf(handler.mybug) >= 0) {
        this.handlerMyBug(webView);
      } else if (url.indexOf(handler.bugBrowse) >= 0) {
        this.handlerBug(webView);
      } else if (url.indexOf(handler.bugView) >= 0) {
        this.handlerBugView(webView);
      } else if (url.indexOf(handler.taskView) >= 0) {
        this.handlerTaskView(webView);
      }
    }
  },
  //重新登录
  reLogin(url, webView) {
    initUrlSetting();
    for (var x in tologinUrls) {
      if (url.indexOf(x) >= 0) {
        webView.loadURL(tologinUrls[x]);
        return
      }
    }
  },
  //跳转到真正登陆地址
  verifyNeedTo: function (url, webView) {
    initUrlSetting();
    for (var x in needToUrls) {
      if (url.indexOf(x) >= 0) {
        webView.loadURL(needToUrls[x]);
        return
      }
    }
    return false
  },
  //验证是否支持自动登录
  verifySuport: function (url) {
    initUrlSetting();
    for (var x in suportUrls) {
      if (url.indexOf(x) >= 0) {
        return suportUrls[x];
      }
    }
    return false
  },
  //自动登录
  aotuLogin: function (dest, webView) {
    console.log("dest")
    console.log(dest)
    if (!dest || !webView) {
      return
    };
    initUrlSetting();
    var time = Date.parse(new Date());
    var beforeTIme = loginHistory[dest.url];
    if (!beforeTIme) {
      loginHistory[dest.url] = time;
    } else if (time - beforeTIme < stopAutoLoginTimeSize) {
      return;
    }
    var script = "";
    switch (dest.appName) {
      case "ava":
        script = this.avaLogin(dest)
        break;
      case "cd":
        script = this.cdLogin(dest)
        break;
      case "alyx":
        script = this.alyxLogin(dest)
        break;
    }

    webView.executeJavaScript(script)
  },
  /*
  加工逻辑 -start
  */
  // 禅道
  handlerTaskView(webView) {
    var script = `
    setTimeout(function(){
      if(document.querySelector('#mainContent .btn-toolbar .add-to-work')){
        return;
      }
      var toolbar=document.querySelector('#mainContent .btn-toolbar');
      var divider=document.querySelector('#mainContent .btn-toolbar .divider');
      var a = document.createElement("a");
      a.setAttribute("class", "btn btn-link iframe add-to-work");
      a.setAttribute("title", "添加到日程");
      a.innerHTML = '<i class="icon icon-delay"></i> <span class="text">添加到日程</span>';
      a.onclick = function(){
        var type=document.querySelector('#currentItem').getAttribute("title")
        var obj={
          bugId:document.querySelector('.page-title .label-id').innerText,
          title:'处理'+document.querySelector('.page-title .text').innerText+'任务',
          type:type,
          msgType:'addPlane'
        }
        console.log("awork::"+JSON.stringify(obj))
      }
      toolbar.insertBefore(a,divider);
    },500)
    `
    webView.executeJavaScript(script)
  },
  handlerBug(webView) {
    var script = `
    setTimeout(function(){
      var tbody=document.querySelector('tbody');
      document.querySelector('thead .c-actions').style.width="170px";
      for(var i=0;i<tbody.childElementCount;i++){
        if(tbody.children[i].querySelector('.c-actions .add-to-work')){
          continue;
        }
        var actions=tbody.children[i].querySelector('.c-actions');
        var a = document.createElement("a");
        a.setAttribute("class", "btn iframe add-to-work");
        a.setAttribute("title", "添加到任务");
        a.innerHTML = '<i class="icon icon-delay"></i>';
        a.onclick = function(){
          var type=document.querySelector('#currentItem').getAttribute("title")
          var obj={
            bugId:this.parentNode.parentNode.getAttribute("data-id"),
            title:'处理'+this.parentNode.parentNode.querySelector('.c-title').getAttribute("title")+'问题',
            type:type,
            msgType:'addPlane'
          }
          console.log("awork::"+JSON.stringify(obj))
        }
        actions.style.width="170px";
        actions.appendChild(a);
      }
    },500)
    `
    webView.executeJavaScript(script)
  },
  handlerBugQAView(webView, id, content) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", 'http://localhost:9000/qa/public/api/v1/qa/search', true);
    xhr.setRequestHeader('content-type', 'application/json');
    var sendData = {
      "search": content,
      "id":id
    };
    //将用户输入值序列化成字符串
    xhr.send(JSON.stringify(sendData));
    //回调
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        var result = JSON.parse(xhr.responseText).data;

        var lswt = "";
        for (var i = 0; i < result.length; i++) {
          var item = result[i];
          lswt += '<div style="padding:8px;color:#616779"">' +
            '<a href="' + item.sourceMap.url + '">'+
            '<div style="padding:4px;font-weight: bold;font-size:1.4rem">'+item.sourceMap.title+'</div></a>';
          var contents = item.hitContent.content;
          var histories = item.hitContent.histories;
          var titles = item.hitContent.title;
          if (contents) {
            for (var j = 0; j < contents.length; j++) {
              lswt += contents[j].replace(/\'/g, '\\\'') + '...<br>';
            }
            lswt += '<span style="color:#9FA6B9">来自类似问题</span>' +
            '</div>';
          } else if (histories) {
            for (var j = 0; j < histories.length; j++) {
              lswt += histories[j].replace(/'/g, '\\\'') + '...<br>';
            }
            lswt += '<span style="color:#9FA6B9">来自类似回复</span>' +
            '</div>';
          } else if (titles) {
            for (var j = 0; j < titles.length; j++) {
              lswt += titles[j].replace(/'/g, '\\\'') + '...<br>';
            }
            lswt += '<span style="color:#9FA6B9">来自类似问题</span>' +
            '</div>';
          } 
        }
        
        var script = `
          setTimeout(function(){
            var sideCol=document.querySelector('#mainContent .side-col');
            var cell=document.querySelector('#mainContent .side-col .cell');
            var a = document.createElement("div");
            a.setAttribute("class", "cell");
            a.innerHTML = ' <div class="tabs">'+
            '  <ul class="nav nav-tabs">'+
            '    <li class="active"><a href="#qaInfo" data-toggle="tab">类似问题</a></li>'+
            '  </ul>'+
            '  <div class="tab-content">'+
            '    <div class="tab-pane active" id="qaInfo" style="max-height: 600px;overflow: auto;">'+
            '`+ lswt + `'
            '    </div>'+
            '  </div>'+
            ' </div>';
            sideCol.insertBefore(a, cell);
          },500)
          `
        webView.executeJavaScript(script)
      }
      
    }
  },
  handlerBugView(webView) {
    var script = `
    setTimeout(function(){
      if(document.querySelector('#mainContent .btn-toolbar .add-to-work')){
        return;
      }
      var toolbar=document.querySelector('#mainContent .btn-toolbar');
      var divider=document.querySelector('#mainContent .btn-toolbar .divider');
      var a = document.createElement("a");
      a.setAttribute("class", "btn btn-link iframe add-to-work");
      a.setAttribute("title", "添加到日程");
      a.innerHTML = '<i class="icon icon-delay"></i> <span class="text">添加到日程</span>';
      a.onclick = function(){
        var type=document.querySelector('#currentItem').getAttribute("title")
        var obj={
          bugId:document.querySelector('.page-title .label-id').innerText,
          title:'处理'+document.querySelector('.page-title .text').innerText+'问题',
          type:type,
          msgType:'addPlane'
        }
        console.log("awork::"+JSON.stringify(obj))
      }

      var detailContent=document.querySelector('#mainContent .detail-content');
      var labelId=document.querySelector('#mainMenu .label-id');
      var obj1={
        content:detailContent.innerText,
        id:labelId.innerText,
        msgType:'handleQA'
      }
      console.log("awork::"+JSON.stringify(obj1))
      toolbar.insertBefore(a,divider);
    },500)
    `
    webView.executeJavaScript(script)
  },
  handlerMyBug(webView) {
    var script = `
    setTimeout(function(){
      var tbody=document.querySelector('tbody');
      document.querySelector('.c-actions-5').style.width="170px";
      for(var i=0;i<tbody.childElementCount;i++){
        if(tbody.children[i].querySelector('.c-actions .add-to-work')){
          continue;
        }
        var actions=tbody.children[i].querySelector('.c-actions');
        var a = document.createElement("a");
        a.setAttribute("class", "btn iframe add-to-work");
        a.setAttribute("title", "添加到日程");
        a.innerHTML = '<i class="icon icon-delay"></i>';
        a.onclick = function(){
          var obj={
            bugId:this.parentNode.parentNode.querySelector('.c-id').innerText,
            title:this.parentNode.parentNode.querySelector('.text-left,.nobr').innerText,
            msgType:'addPlane'
          }
          console.log("awork::"+JSON.stringify(obj))
        }
        actions.style.width="170px";
        actions.appendChild(a);
      }
    },500)
    `
    webView.executeJavaScript(script)
  },
  //阿里邮箱
  /*
  加工逻辑 -end
  */

  //自动登录逻辑 -start
  //阿里邮箱
  alyxLogin(dest) {
    var sc = `
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("input", true, true);

    var ut_pass=document.querySelector('input[type="password"]');
    var ut_name=document.querySelector('input[type="text"]');

    ut_name.value='`+ dest.name + `';
    
    ut_pass.value='`+ dest.password + `';
    
    setTimeout(function(){
      ut_name.focus();
      ut_name.click();
      ut_name.dispatchEvent(evt);

      ut_pass.focus();
      ut_pass.click();
      ut_pass.dispatchEvent(evt);

      var checkcode=document.querySelector('#login_checkcode');
      if(!checkcode || checkcode == null) {
        return
      }
      document.querySelector('button[type="submit"]').click();
    },100)
    `
    return sc;

  },
  //奥威亚应用平台
  avaLogin(dest) {
    var sc = `
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("input", true, true);

    var ut_pass=document.querySelector('input[type="password"]');
    var ut_name=document.querySelector('input[type="text"]');
    
    ut_name.value='`+ dest.name + `';
    
    ut_pass.value='`+ dest.password + `';
    
    setTimeout(function(){
      ut_name.focus();
      ut_name.click();
      ut_name.dispatchEvent(evt);

      ut_pass.focus();
      ut_pass.click();
      ut_pass.dispatchEvent(evt);

      document.querySelector('.footer button').click();
    },100)
    `;
    return sc;
  },
  //禅道
  cdLogin(dest) {
    var sc = `
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("input", true, true);

    var ut_pass=document.querySelector('input[type="password"]');
    var ut_name=document.querySelector('input[type="text"]');
    
    ut_name.value='`+ dest.name + `';
    
    ut_pass.value='`+ dest.password + `';
    
    setTimeout(function(){
      ut_name.focus();
      ut_name.click();
      ut_name.dispatchEvent(evt);

      ut_pass.focus();
      ut_pass.click();
      ut_pass.dispatchEvent(evt);

      document.querySelector('button[type="submit"]').click();
    },100)
    `
    return sc;
  }
}

//初始化禅道
var initUrlSetting = () => {
  if (initUrl) { return }
  let cdUrl = localStorage.getItem("cdUrl");

  if (cdUrl) {
    cdUrl = cdUrl.trim()
    if (cdUrl.charAt(cdUrl.length - 1) != '/') {
      cdUrl = cdUrl + '/'
    }
    tologinUrls[cdUrl] = cdUrl + 'user-login.html'
    suportUrls[cdUrl + 'user-login'] = {
      dest: cdUrl,
      appName: 'cd'
    }
    urlTag.cd = cdUrl
  }
  initUrl = true
}

export {
  ut
};
